package com.supor.aiot.common.base;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Lifecycle;
import androidx.viewbinding.ViewBinding;


import com.supor.aiot.common.R;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public abstract class BaseDialogFragment<T extends ViewBinding> extends DialogFragment implements View.OnClickListener {

    protected T binding;
    protected int layout = -1;
    protected int dialogGravity = -1;
    private int animRes = -1;
    private int dialogStyle = -1;
    private int showX = -1;
    private int showY = -1;

    private DialogShowHideListener listener;
    private Dialog dialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        if (dialog == null) {
            dialog = new Dialog(getActivity(), dialogStyle == -1 ? R.style.dialog_fragment_base : dialogStyle);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
            dialog.setContentView(initBinding(getLayoutInflater()));
            if (animRes != -1) {
                Window window = dialog.getWindow();
                if (window != null) {
                    window.setWindowAnimations(animRes);
                }
            }
//            initView(dialog);
            initView();
            initEvents();
            dialog.setCanceledOnTouchOutside(true); // 外部点击取消

            // 设置宽度为屏宽, 设置窗体显示位置。
            if (dialogGravity != -1) {
                Window window = dialog.getWindow();
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.gravity = dialogGravity;
//                lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平
                window.setAttributes(lp);
            }
            if (showX != -1 && showY != -1) {
                Window window = dialog.getWindow();
                WindowManager.LayoutParams lp = window.getAttributes();
                //设置显示位置
                lp.x = showX;
                lp.y = showY;
//                lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平
                dialog.onWindowAttributesChanged(lp);
            }
            onDialogCreated();
        } else {
            initNotify();
        }
        return dialog;

    }

    private View initBinding(LayoutInflater inflater) {
        Type superclass = getClass().getGenericSuperclass();
        Class<?> aClass = (Class<?>) ((ParameterizedType) superclass).getActualTypeArguments()[0];
        try {
            Method method = aClass.getDeclaredMethod("inflate", LayoutInflater.class);
            binding = (T) method.invoke(null, inflater);
            return binding.getRoot();
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

//    protected void findViewById(int res){
//
//    }

    public void onDialogCreated() {

    }

    /**
     * 设置对话框位置
     *
     * @param gravity
     */
    protected void setDialogGravity(int gravity) {
        dialogGravity = gravity;
    }

    /**
     * 设置布局资源id
     *
     * @param layout
     */
    protected void setDialogContentRes(int layout) {
        this.layout = layout;
    }

    /**
     * 设置dialog动画
     *
     * @param animRes
     */
    protected void setDialogAnimaRes(int animRes) {
        this.animRes = animRes;
    }

    /**
     * 设置dialog style
     *
     * @param style
     */
    protected void setStyle(int style) {
        this.dialogStyle = style;
    }

    public boolean isShowing() {
        if (null != dialog) {
            return dialog.isShowing();
        } else {
            return false;
        }
    }

    public void setShowLocation(int x, int y) {
        this.showX = x;
        this.showY = y;
    }

    public Dialog getDialog() {
        return dialog;
    }

    @Deprecated
    protected void initView(Dialog dialog) {

    }

    protected abstract void initView();

    protected abstract void initEvents();

    protected abstract void initNotify();

    @Override
    public void dismiss() {
        super.dismissAllowingStateLoss();
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        try {
            Field mDismissed = DialogFragment.class.getDeclaredField("mDismissed");
            mDismissed.setAccessible(true);
            mDismissed.set(this, false);
            Field mShownByMe = DialogFragment.class.getDeclaredField("mShownByMe");
            mShownByMe.setAccessible(true);
            mShownByMe.set(this, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        FragmentTransaction ft = manager.beginTransaction();
        ft.add(this, tag);
        ft.commitAllowingStateLoss();
        if (null != listener) {
            listener.showHide(true);
        }
    }

    public void setOnDialogShowHideListener(DialogShowHideListener listener) {
        this.listener = listener;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        if (null != listener) {
            listener.showHide(false);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    @Override
    public void onClick(View v) {
        if (fastClick())
            widgetClick(v);
    }

    /**
     * [防止快速点击]
     *
     * @return
     */
        public boolean fastClick() {
            long lastClick = 0;
            if (System.currentTimeMillis() - lastClick <= 1000) {
                return false;
            }
            lastClick = System.currentTimeMillis();
            return true;
    }

    /**
     * View点击
     **/
    public abstract void widgetClick(View v);


    public interface DialogShowHideListener {
        void showHide(boolean isShow);
    }

    @Nullable
    protected <T extends View> T findViewById(@IdRes int res) {
        if (null != dialog) {
            return dialog.findViewById(res);
        }
        return null;
    }

}
